package com.service.loan.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.client.model.pojo.bank.ArBankcard;
import com.client.model.pojo.loan.AiruiLoan;
import com.client.model.pojo.loan.AiruiLoanProduct;
import com.client.model.pojo.user.ArUser;
import com.client.model.vo.common.Result;
import com.client.model.vo.common.ResultCodeEnum;
import com.client.model.vo.creditLoanVo.RulerVo;
import com.service.loan.feignService.BankCardFeignService;
import com.service.loan.service.AiruiLoanProductService;
import com.service.loan.service.AiruiLoanService;
import com.service.loan.mapper.AiruiLoanMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * @author liuwenju
 * @description 针对表【airui_loan】的数据库操作Service实现
 * @createDate 2024-04-01 20:58:48
 */
@Slf4j
@Service
public class AiruiLoanServiceImpl extends ServiceImpl<AiruiLoanMapper, AiruiLoan>
        implements AiruiLoanService {
    @Autowired
    private AiruiLoanMapper airuiLoanMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private BankCardFeignService bankCardFeignService;
    @Autowired
    private AiruiLoanProductService airuiLoanProductService;

    @Override
    public Result<List<AiruiLoan>> myLoan(String token) {
        //根据token从redis中取出当前用户的信息
        String s = redisTemplate.opsForValue().get("user:login" + token);
        ArUser arUser = JSON.parseObject(s, ArUser.class);
        //根据用户的id查询当前用户所有的贷款信息
        QueryWrapper<AiruiLoan> airuiLoanQueryWrapper = new QueryWrapper<>();
        airuiLoanQueryWrapper.eq("uid", arUser.getUid());
        List<AiruiLoan> airuiLoanList = this.airuiLoanMapper.selectList(airuiLoanQueryWrapper);
        return Result.build(airuiLoanList, ResultCodeEnum.SUCCESS);
    }

    @Override
    public Result<String> reBackLoan(RulerVo rulerVo, String token) {
        log.info("rulerVo-------->{}", rulerVo);
        ArBankcard arBankcard = null;
        AiruiLoan airuiLoan = this.airuiLoanMapper.selectById(rulerVo.getId());
        log.info("当前的贷款信息----------->{}",airuiLoan);
        //在redis中取出用户的信息
        String s = redisTemplate.opsForValue().get("user:login" + token);
        ArUser arUser = JSON.parseObject(s, ArUser.class);
        log.info("当前登录的用户信息-------->{}", arUser);
        if (ObjectUtil.isEmpty(rulerVo.getCardNum())) {
            //如果银行卡号是空的，那么证明默认使用绑定的银行卡进行操作
            //通过信用卡中的还款信息来判断用户输入的密码是否正确
            arBankcard = this.bankCardFeignService.getCreditCardByCardNum(airuiLoan.getCardNum(),rulerVo.getPassword());
        } else {
            arBankcard = this.bankCardFeignService.getCreditCardByCardNum(rulerVo.getCardNum(), rulerVo.getPassword());
        }
        log.info("还款的银行卡信息---------->{}",arBankcard);

        //通过传入的id查询当前的贷款信息
        //当前用户的可以有多个贷款通过一张银行卡来还

        if (ObjectUtil.isEmpty(arBankcard)) {
            return Result.build(null, 400, "支付密码错误");
        }
        //不等于500，则代表密码判断成功 此时判断当前银行卡余额是否满足还款需求

        //下面这段代码是不对的，我们应该去跟贷款表中的贷款月供进行比对，数据库明显没有这个字段
        //没有这个字段也不会妨碍我们去操作
        //通过贷款信息去查询贷款的产品信息
        QueryWrapper<AiruiLoanProduct> airuiLoanProductQueryWrapper = new QueryWrapper<>();
        airuiLoanProductQueryWrapper.eq("id", airuiLoan.getLid());

        AiruiLoanProduct airuiLoanProduct = this.airuiLoanProductService.getOne(airuiLoanProductQueryWrapper);
        log.info("airuiLoanProduct----------->{}",airuiLoanProduct);
        Integer loanTime = Integer.valueOf(airuiLoanProduct.getLoanTime());
        loanTime = loanTime * 12;
        log.info("还款时长-------->{}（月）", loanTime);
        BigDecimal bigDecimal = new BigDecimal(airuiLoanProduct.getLoanTime());
        log.info("bigDecimal-------->{}",bigDecimal);
        //每年需还本金
        BigDecimal divide = airuiLoan.getLcount().divide(bigDecimal,2);
        log.info("divide-------------->{}",divide);
        //本金/年 * 利率/12  每月的月供利息
        BigDecimal reBackMonthRice = divide.multiply(airuiLoanProduct.getRateNumber()).divide(new BigDecimal(12));
        if (arBankcard.getBalance().compareTo(reBackMonthRice) < 0) {
            //则证明余额不够
            return Result.build(null, 500, "余额不足");
        }
        //余额充足，先扣除银行卡中的钱
        arBankcard.setBalance(arBankcard.getBalance().subtract(reBackMonthRice));
        this.bankCardFeignService.savePrice(arBankcard);
        //更新贷款表中的还款日期到下个月的1号
        airuiLoan.setBorrowDate(DateUtil.offsetDay(airuiLoan.getBorrowDate(), 30));
        this.airuiLoanMapper.updateById(airuiLoan);
        //todo 迭代需要考虑的---->如果有节假日应当考虑节假日如何跳过，如果用户逾期未归还如何记录这些未还记录，扣取信用积分

        return Result.build(null, 200, "还款成功");
    }

    @Override
    public Result<String> canAffordIt(RulerVo rulerVo, String token) {
        log.info("rulerVo-------->{}", rulerVo);
        ArBankcard arBankcard = null;
        AiruiLoan airuiLoan = this.airuiLoanMapper.selectById(rulerVo.getId());
        log.info("当前的贷款信息----------->{}",airuiLoan);
        //在redis中取出用户的信息
        String s = redisTemplate.opsForValue().get("user:login" + token);
        ArUser arUser = JSON.parseObject(s, ArUser.class);
        log.info("当前登录的用户信息-------->{}", arUser);
        if (ObjectUtil.isEmpty(rulerVo.getCardNum())) {
            //如果银行卡号是空的，那么证明默认使用绑定的银行卡进行操作
            //通过信用卡中的还款信息来判断用户输入的密码是否正确
            arBankcard = this.bankCardFeignService.getCreditCardByCardNum(airuiLoan.getCardNum(),rulerVo.getPassword());
        } else {
            arBankcard = this.bankCardFeignService.getCreditCardByCardNum(rulerVo.getCardNum(), rulerVo.getPassword());
        }
        log.info("还款的银行卡信息---------->{}",arBankcard);

        //通过传入的id查询当前的贷款信息
        //当前用户的可以有多个贷款通过一张银行卡来还

        if (ObjectUtil.isEmpty(arBankcard)) {
            return Result.build(null, 400, "支付密码错误");
        }
        //不等于500，则代表密码判断成功 此时判断当前银行卡余额是否满足还款需求

        //下面这段代码是不对的，我们应该去跟贷款表中的贷款月供进行比对，数据库明显没有这个字段
        //没有这个字段也不会妨碍我们去操作
        //通过贷款信息去查询贷款的产品信息
        QueryWrapper<AiruiLoanProduct> airuiLoanProductQueryWrapper = new QueryWrapper<>();
        airuiLoanProductQueryWrapper.eq("id", airuiLoan.getLid());

        AiruiLoanProduct airuiLoanProduct = this.airuiLoanProductService.getOne(airuiLoanProductQueryWrapper);
        log.info("airuiLoanProduct----------->{}",airuiLoanProduct);
        Integer loanTime = Integer.valueOf(airuiLoanProduct.getLoanTime());
        loanTime = loanTime * 12;
        log.info("还款时长-------->{}（月）", loanTime);
        BigDecimal bigDecimal = new BigDecimal(airuiLoanProduct.getLoanTime());
        log.info("bigDecimal-------->{}",bigDecimal);
        //每年需还本金
        BigDecimal divide = airuiLoan.getLcount().divide(bigDecimal,2);
        log.info("divide-------------->{}",divide);
        //本金/年 * 利率/12  每月的月供利息
        BigDecimal reBackMonthRice = divide.multiply(airuiLoanProduct.getRateNumber()).divide(new BigDecimal(12));
        if (arBankcard.getBalance().compareTo(reBackMonthRice) < 0) {
            //则证明余额不够
            return Result.build(null, 500, "余额不足");
        }
        return Result.build(null, 200, "余额充足");
    }

}




